﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Runtime.Serialization.Json;
using System.Text.RegularExpressions;
using System.Collections.Specialized;
using System.Web;

namespace GtsServer.Common
{
    public class JsonParser
    {
        public static string JsonSerializer<T>(T t)
        {
            DataContractJsonSerializer ser = new DataContractJsonSerializer(typeof(T));
            MemoryStream ms = new MemoryStream();
            ser.WriteObject(ms, t);
            string jsonString = Encoding.UTF8.GetString(ms.ToArray());
            ms.Close();
            return jsonString;
        }
     
        public static T JsonDeserialize<T>(string json)
        {
            //json = ReplaceN(json);
            ////json = ReplaceT(json);
            json=json.Replace("\n", "\\n").Replace("\t", "\\t");
            DataContractJsonSerializer serializer = new DataContractJsonSerializer(typeof(T));
            MemoryStream mStream = new MemoryStream(Encoding.UTF8.GetBytes(json));
            return (T)serializer.ReadObject(mStream);
        }
        private static string ReplaceN(string value)
        {

            //Regex regex = new Regex(@"[\n]+");
            //MatchCollection collection = regex.Matches(value);
            //foreach (Match item in collection)
            //{
            //    string replace = item.Value.Replace(@"\n", "\\n");
            //    value = value.Replace(item.Value, replace);
            //}
            return value.Replace("\n", "\\n");
        }
        private static string ReplaceT(string value)
        {
            Regex regex = new Regex(@"[\t]+");
            MatchCollection collection = regex.Matches(value);
            foreach (Match item in collection)
            {
                string replace = item.Value.Replace("\t", "\\t");
                value = value.Replace(item.Value, replace);
            }
            return value;
        }
		/// <summary>
		/// 格式化 Json 字符串，每个值都添加 ""
		/// </summary>
		/// <param name="json">json字符串</param>
		/// <returns>格式化后的字符串</returns>
		/// <remarks>
		///		Create：宋飞  2011-11-9
		/// </remarks>
		public static string FormatJson(string json)
		{
			string format = string.Empty;
			Regex regex = new Regex(@":\w+,");
			MatchCollection collection = regex.Matches(json);
			string replace = string.Empty;
			foreach(Match item in collection)
			{
				replace = item.Value.Replace(":", ":\"").Replace(",", "\",");
				json = json.Replace(item.Value, replace);
			}
			return json;
		}
    }
}
